package com.iqilu.ksd.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.LoginActivity;
import com.iqilu.ksd.activity.SubsDetailActivity;
import com.iqilu.ksd.bean.SubsItemBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.utils.JSONUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.RequestBody;

/**
 * Created by Coofee on 2017/4/20.
 */

public class SubsListFragment extends BaseFragment {

    private UserBean user;
    private int position;
    private ArrayList<SubsItemBean> list;
    private ArrayList<SubsItemBean> childList;

    private View view;
    private GridView gvList;
    private SubsAdapter adapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = ((MyApplication) context.getApplicationContext()).getUser();
        list = (ArrayList<SubsItemBean>) getArguments().getSerializable("list");
        position = getArguments().getInt("position");
        childList = new ArrayList<SubsItemBean>();
        childList.add(list.get(position * 2));
        childList.add(list.get(position * 2 + 1));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
            return view;
        }
        view = inflater.inflate(R.layout.fragment_subslist, null);
        gvList = (GridView) view.findViewById(R.id.gv_list);
        adapter = new SubsAdapter();
        gvList.setAdapter(adapter);
        return view;
    }

    private void toSubscribe(int current) {
        if (user == null || user.getId() < 1) {
//            Toast.makeText(context,R.string.not_login,Toast.LENGTH_SHORT).show();
            startActivity(new Intent(context, LoginActivity.class));
            return;
        }
        if (childList.get(current).getSubscribed() == 1) { //取消订阅
            delSubscribe(childList.get(current).getCatid(), current);
        } else {
            addSubscribe(childList.get(current).getCatid(), childList.get(current).getCatname(), current);
        }
    }

    private void addSubscribe(int catId, String catName, final int current) {
        String url = Api.URL_SUBSCRIBE + "?catid=" + catId + "&catname=" + catName + "&type=article";
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(RequestBody.create(null, "something"))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(context, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
//                            subscribed = 1;
//                            btSubs.setImageResource(R.drawable.bt_subscribed);
                            childList.get(current).setSubscribed(1);
                            adapter.notifyDataSetChanged();
                            Toast.makeText(context, R.string.my_add_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void delSubscribe(int catId, final int current) {
        String url = Api.URL_SUBSCRIBE + "?catid=" + catId + "&type=article";
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(context, R.string.my_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
//                    subscribed = 0;
//                    btSubs.setImageResource(R.drawable.bt_subscribe);
                    childList.get(current).setSubscribed(0);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(context, R.string.my_del_success, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, R.string.my_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    class SubsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public Object getItem(int position) {
            return childList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            final SubsItemBean data = childList.get(position);
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.list_item_subs_lightning, null);
                holder.imgThumb = (SimpleDraweeView) convertView.findViewById(R.id.img_thumb);
                holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
                holder.btSubs = (ImageView) convertView.findViewById(R.id.bt_subs);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.imgThumb.setImageURI(Uri.parse("" + data.getThumb()));
            holder.tvTitle.setText("" + data.getCatname());
            if (data.getSubscribed() == 1) {
                holder.btSubs.setImageResource(R.drawable.bt_subscribed);
            } else {
                holder.btSubs.setImageResource(R.drawable.bt_subscribe);
            }
            holder.btSubs.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toSubscribe(position);
                }
            });
            holder.imgThumb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, SubsDetailActivity.class);
                    intent.putExtra("catid", data.getCatid());
                    startActivity(intent);
                }
            });
            return convertView;
        }

        class ViewHolder {
            SimpleDraweeView imgThumb;
            TextView tvTitle;
            ImageView btSubs;
        }
    }
}
